package handler

import (
	"bytes"
	"encoding/json"
	uuid "github.com/satori/go.uuid"
	"log"
	"net/http"
	"src/modle"
)

const (
	Pass         = 0 //通过
	Forbid       = 1 //未通过
	Filed        = 2 //异常
	ServiceCode  = "5acf8444978c66617987f1c1a7781194"
	CustomerName = "TINDAT"
	Factory      = "GoldFinance"
	HighRisk     = 5 //高
	MidRisk      = 4 //中
	LowRisk      = 3 //低
	Agency       = 2 //疑似
	safe         = 1 //安全
)

func BlackListCheck(idCardNo, mobileNo string) (*modle.RiskAssessmentResp, int) {
	var pass int
	requestId := GetUuid()
	url := "http://goldfinance.finpower.org:9094/record/info?requestId=" + requestId + "&serviceCode=" + ServiceCode + "&customerName=" + CustomerName
	body := make(map[string]string)
	body["idCardNo"] = idCardNo
	body["mobileNo"] = mobileNo
	resp, e := Post(url, body)
	if e != nil {
		pass = Filed
		log.Println(e.Error())
		return nil, pass
	}
	if resp.RetCode != 0 {
		pass = Filed
		log.Println("retCode =", resp.RetCode, resp.RetDesc)
		return nil, pass
	}
	var re modle.RiskAssessmentResp
	var si modle.SingleResult
	var ss []modle.SingleResult
	si.Factory = Factory
	//todo:待优化，由于这部分传回的值都是01字符串，所以解析的时候没有办法omitempty，方案：反射
	if resp.RetData.BlIdHighRisk == "1" {
		pass = Forbid
		si.IdRisk = HighRisk
	} else if resp.RetData.BlIdMidRisk == "1" {
		pass = Forbid
		si.IdRisk = MidRisk
	} else if resp.RetData.BlIdLowRisk == "1" {
		si.IdRisk = LowRisk
	} else if resp.RetData.BlIdAgency == "1" {
		si.IdRisk = Agency
	} else {
		si.IdRisk = safe
	}

	if resp.RetData.BlMobHighRisk == "1" {
		pass = Forbid
		si.PhoneRisk = HighRisk
	} else if resp.RetData.BlMobMidRisk == "1" {
		pass = Forbid
		si.PhoneRisk = MidRisk
	} else if resp.RetData.BlMobLowRisk == "1" {
		si.PhoneRisk = LowRisk
	} else if resp.RetData.BlMobAgency == "1" {
		si.PhoneRisk = Agency
	} else {
		si.PhoneRisk = safe
	}
	ss = append(ss, si)
	re.BlackLists = ss
	//log.Printf("GoldFinance风险评估结果：%+v \n", re)
	return &re, pass
}

func GetUuid() string {
	uuid.NewV4()
	id := uuid.NewV4()
	return id.String()
}

func Post(url string, body map[string]string) (*modle.RetTotal, error) {
	//add post body
	var bodyJson []byte
	var req *http.Request
	if body != nil {
		var err error
		bodyJson, err = json.Marshal(body)
		if err != nil {
			log.Println(err)
			//return nil, errors.New("http post body to json failed")
			return nil, err
		}
	}
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyJson))
	if err != nil {
		log.Println(err)
		//return nil, errors.New("new request is fail: %v \n")
		return nil, err
	}
	req.Header.Set("Content-type", "application/json")

	client := &http.Client{}
	log.Printf("Go POST URL : %s \n", req.URL.String())
	log.Printf("Go POST Body : %s \n", req.Body)
	resp, e := client.Do(req)
	if e != nil {
		return nil, e
	}
	RetStruct := &modle.RetTotal{}
	if err := json.NewDecoder(resp.Body).Decode(RetStruct); err != nil {
		log.Println(err.Error())
		return nil, err
	}
	log.Printf(" 响应: %+v \n", RetStruct)
	return RetStruct, nil
}


